package com.example.image.impl;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.image.IImageLoader;
import com.example.image.ImageOptions;

import java.io.File;
import java.lang.ref.SoftReference;

public class GlideImpl implements IImageLoader {
    @Override
    public void loadFromUrl(Context context, String url, ImageView target, ImageOptions options) {
        realLoadImage(context,url,target,options);
    }

    @Override
    public void loadFromFile(Context context, File file, ImageView target, ImageOptions options) {
        realLoadImage(context,file,target,options);
    }

    @Override
    public void loadFromResource(Context context, int resourceId, ImageView target, ImageOptions options) {
        realLoadImage(context,resourceId,target,options);
    }

    /**
     * 加载图片到ImageView方法
     */
    private void realLoadImage(Context context, Object url, ImageView target, ImageOptions options) {
        SoftReference<Context> softReference=new SoftReference<>(context);
        RequestBuilder<Drawable> builder = Glide.with(softReference.get()).load(url);
        setGlideOptions(builder,options);
        builder.into(target);
    }


    /**
     * 处理可选参数方法
     */
    private void setGlideOptions(RequestBuilder<Drawable> builder, ImageOptions options) {
        if (options==null){
            return;
        }

        RequestOptions glideOptions=new RequestOptions();


        //占位图
        if (options.getPlaceImage()>0){
            glideOptions.placeholder(options.getPlaceImage());
        }

        //错误图
        if (options.getErrorImage()>0){
            glideOptions.error(options.getErrorImage());
        }

        //圆形图
        if (options.isCircle()){
            glideOptions.circleCrop();
        }

        //内存缓存
        if (!options.isMemoryCache()){
            glideOptions.skipMemoryCache(true);
        }

        //磁盘缓存
        if (!options.isDiskCache()){
            glideOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
        }


        builder.apply(glideOptions);

    }
}
